package com.hrbxlh.virtualization.service.impl;

import com.hrbxlh.virtualization.dao.ConfigMapper;
import com.hrbxlh.virtualization.param.ConfigUpdateParam;
import com.hrbxlh.virtualization.pojo.Config;
import com.hrbxlh.virtualization.pojo.ConfigExample;
import com.hrbxlh.virtualization.service.ConfigService;
import com.hrbxlh.virtualization.service.ContainerService;
import com.hrbxlh.virtualization.vo.ConfigVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * @author cheer
 */
@Service
public class ConfigServiceImpl implements ConfigService, ApplicationListener<ContextRefreshedEvent> {

    private Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private ScheduledFuture<?> future;

    private Boolean containerDeleted = true;

    private Integer imageQuota = 7;

    @Autowired
    private ContainerService containerService;

    @Autowired
    private ConfigMapper configMapper;

    @Override
    public Config queryConfigFromDB() {
        ConfigExample configExample = new ConfigExample();
        List<Config> configList = configMapper.selectByExample(configExample);
        if (CollectionUtils.isNotEmpty(configList)) {
            return configList.get(0);
        }
        return null;
    }

    @Override
    public ConfigVO queryConfig() {
        ConfigVO configVO = new ConfigVO();
        configVO.setContainerDeleted(containerDeleted);
        configVO.setImageQuota(imageQuota);
        return configVO;
    }

    @Override
    public synchronized void updateConfig(ConfigUpdateParam configUpdateParam) {
        if (configUpdateParam == null) {
            return;
        }

        updateContainerDelete(configUpdateParam.getContainerDeleted());

        updateImageQuota(configUpdateParam.getImageQuota());

        updateConfigToDB();
    }

    private void updateContainerDelete(Boolean isDeleted) {
        if (isDeleted != null) {
            if (containerDeleted != isDeleted) {
                if (isDeleted) {
                    startContainerDelete();
                } else {
                    stopContainerDelete();
                }
            }

            containerDeleted = isDeleted;
        }
    }

    private void updateImageQuota(Integer quota) {
        if (quota != null && quota >= 0 && quota <= 99) {
            imageQuota = quota;
        }
    }

    private void updateConfigToDB() {
        Config config = queryConfigFromDB();
        if (config == null) {
            config = new Config();
            config.setContainerDeleted(containerDeleted);
            config.setImageQuota(imageQuota);
            configMapper.insertSelective(config);
        } else {
            config.setContainerDeleted(containerDeleted);
            config.setImageQuota(imageQuota);
            configMapper.updateByPrimaryKeySelective(config);
        }
    }

    private void startContainerDelete() {
        future = threadPoolTaskScheduler.schedule(() -> {
            logger.info("定时删除容器开启");
            try {
                containerService.deleteAllContainers();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            logger.info("定时删除容器结束");
        }, new CronTrigger("0 0 1 * * *"));
    }

    private void stopContainerDelete() {
        if (future != null) {
            future.cancel(true);
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            Config config = queryConfigFromDB();
            if (config != null) {
                containerDeleted = config.getContainerDeleted();
                imageQuota = config.getImageQuota();
            }

            if (containerDeleted) {
                startContainerDelete();
            }
        }
    }

    @Override
    public Integer getImageQuota() {
        return imageQuota;
    }
}
